package com.example.terminalservice.filter;

import com.example.terminalservice.common.CodeEnum;
import com.example.terminalservice.common.Constants;
import com.example.terminalservice.common.Result;
import com.example.terminalservice.pojo.User;
import com.example.terminalservice.utils.JwtUtils;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author 28142
 * @description Jwt过滤器
 * @date 2023/8/14 1:08
 */
@Component
public class JwtFilter extends OncePerRequestFilter {
    @Autowired
    private ObjectMapper objectMapper;
    private final AntPathMatcher pathMatcher = new AntPathMatcher();

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        System.out.println("==========jwt filter=========");
        // 对所有websocket请求放行
        if (pathMatcher.match("/terminal/**", request.getRequestURI())) {
            filterChain.doFilter(request, response);
        }
        // 如果是白名单请求，放行；否则校验jwt
        if (!Arrays.asList(Constants.URL_WHITELIST).contains(request.getRequestURI())) {
            response.setContentType("application/json");
            response.setCharacterEncoding("UTF-8");
            String header = request.getHeader("Authorization");
            if (header == null || !header.startsWith("Bearer ")) {
                System.out.println("=========header error===========");
                PrintWriter writer = response.getWriter();
                writer.write(objectMapper.writeValueAsString(Result.error(CodeEnum.CODE_404)));
                writer.flush();
                return;
            }
            String token = header.replace("Bearer ", "");
            if (token == null) {
                System.out.println("=========token error===========");
                PrintWriter writer = response.getWriter();
                writer.write(objectMapper.writeValueAsString(Result.error(CodeEnum.CODE_404)));
                writer.flush();
                return;
            }
            // 解析token
            User user = JwtUtils.parseToken(token, User.class);
            System.out.println(user);
            List<SimpleGrantedAuthority> authorities = user.getAuthorityList().stream().map(SimpleGrantedAuthority::new).collect(Collectors.toList());
            // 用户名密码认证token
            UsernamePasswordAuthenticationToken authenticationToken =
                    new UsernamePasswordAuthenticationToken(user, null, authorities);
            // 将token放到安全上下文
            SecurityContextHolder.getContext().setAuthentication(authenticationToken);
        }
        filterChain.doFilter(request, response);
    }
}
